<?php
	
	require_once(dirname(__FILE__) . "/../core/safeParam.php");
	
	$result = false;
	$error = false;
	
	
	//SESSION
	if ((!isset($_SESSION['userid'])) or ($_SESSION['userid'] == '' ) ) {
		$loggedIn = 0;
		$showRegForm = false;
	} else {
  		$loggedIn=1;
  		$showRegForm = true;
	}
	
	
	//MOSTRAR LOGIN O REGISTRO	
	if( (isset($_GET['reg'])) && ($_GET['reg'] == 1)){
		$showRegForm = true;
	}
	
	if(isset($_GET['return']) && ($_GET['return'] != '')){
		$error 	= "Error: Debe estar loqueado para poder pedir.";
		$smarty->assign('return', $_GET['return']);
	} else {
		$smarty->assign('return', 1);
	}
	
	if ($showRegForm) {
		$smarty->assign('hide_login', 'display:none');
	} else {
		$smarty->assign('hide_register', 'display:none');
	}
	
	
	
	//LOGIN
	if(isset($_REQUEST['action']) && $_REQUEST['action'] == $lang['login'] ){
		$result = checkPassword($_POST['email'], $_POST['password']);
		
		if (!$result['valid_login']) {
			$error = "Error: Usuario o contraseña no válido";
  		} else {
  			//Login válido
    		$_SESSION['userid'] = $result['id'];
    		    		
    		if (isset($_POST['return'])) {
    			header("Location: ". $_POST['return'] ." ");
    			exit(0);
    		}
			
			header("Location: " . $_SERVER['HTTP_REFERER']);
			exit(0);
  		}
	}
	

		
	//REGISTRO
	if (isset($_REQUEST['action']) && $_REQUEST['action'] == $lang['reg_register_button']) {
		//validation
		$check_user_exists = $database->select("SELECT id FROM users where email='" . $_POST['email'] . "'");
		
		if (empty($_POST['name']) || empty($_POST['last_name']) || empty($_POST['email']) || empty($_POST['address']) || empty($_POST['phone']) ) {
			$error .= $lang['reg_error'];
  		} elseif ($check_user_exists != FALSE) {
  			$error .= $lang['reg_error_exists'];
  		} else {
  			$user = array();
    		$user['name']      = $_POST['name'];
    		$user['last_name'] = $_POST['last_name'];
    		$user['email']     = $_POST['email'];
    		$user['address']   = $_POST['address'];
    		$user['city']      = "Cordoba";
    		$user['state']     = "Cordoba";
    		$user['phone']     = $_POST['phone'];
    		$user['password']  = md5($_POST['password']);
    		
    		//insert user  
    		$database->insert_array('users', $user);
    		    		
    		//mail
    		$msgBody ='<html>
			<head>
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		
				<style type="text/css">			
					.body h2{
						font-weight: normal;
					}
			
					.body p{
						font-family: sans-serif;
						font-size: 12px;
						font-weight: normal;
					}
			
					.footer{
						height: 30px;
						
						font-family: sans-serif;
						font-size: 12px;
						font-weight: normal;			
					}
				</style>
			</head>
	
	
			<body>		
				<div class="body">
					<h2>
						<img src="http://www.delivery351.com/images/txtBlack.png" >
					</h2>

					<p>
						Estimado/a <b>'. $user['name'] .'</b>: 
						
						<br />
						<br />
				
						¡FELICITACIONES! Tu cuenta de <b><i><u>Delivery351</u></i></b> ha sido configurada correctamente.
				
						<br />
						<br />
						<br />
				
						Podes iniciar sesion utilizando los siguientes datos:
				
						<br />
						<br />
				
						E-mail:		<b>'. $user['email'] .'</b>

						<br />

						Password:	<b>'. $_POST['password'] .'</b>
				
						<br />
						<br />
						
						Por favor, guarda estos datos en un lugar seguro. 
				
						<br />
						<br />
						
						Para iniciar sesion <a href="http://www.delivery351.com/index.php?act=reg">clic aqui</a>
						
						<hr>
					</p>			
				</div>
		
				<div class="footer">
					© 2013 Delivery351.com - El Delivery de Córdoba - Todos los derechos reservados. 
				</div>
			</body>
			</html>';   
    		
    		//require_once('configMail.php');
    		require_once('phpmailer/class.phpmailer.php');
    		
    		$mail             = new PHPMailer(); 				// defaults to using php "mail()"
    		
    		$mail->SetFrom('info@delivery351.com', 'info@delivery351.com');
    		$mail->AddReplyTo("info@delivery351.com","info@delivery351.com");
    		$mail->Subject    = "Registro en Delivery351";
    		    		
    		$address = $user['email'];
    		$mail->AddAddress($address);
    		$mail->AddBCC("patricioa183@hotmail.com"); 
    		
    		$mail->MsgHTML($msgBody);
    		    		
    		$mail->send();
    		
    		$_SESSION['userid'] = mysql_insert_id();
    		if (isset($_POST['return'])) {
    			header("Location: ". $_POST['return'] ." ");
      		exit(0);
    		} else {
    			header("Location: " . $_SERVER['HTTP_REFERER']);
      		exit(0);
    		}
    	}
  	}

	
	
	//GUARDAR MODIFICACIÓN DE PERFIL
	if (isset($_REQUEST['action']) && $_REQUEST['action'] == $lang['reg_save_button']) {
		$user = array();
  		$user['name']      = $_POST['name'];
  		$user['last_name'] = $_POST['last_name'];
  		$user['email']     = $_POST['email'];
  		$user['address']   = $_POST['address'];
  		$user['city']      = "Cordoba";
  		$user['state']     = "Cordoba";
  		$user['phone']     = $_POST['phone'];
  		
  		if (isset($_POST['password']) && trim($_POST['password']) != ""){
  			$userid = checkPassword($_POST['email'], $_POST['current_password']);
  			
  			if (!$userid){
  				$error .= $lang['reg_incorrect_password'];
  			} else {
  				// old password matches. 
    			if ($_POST['password'] != $_POST['password_confirm']){
    				$error .= $lang['reg_passwords_not_match'];
     			} else {
     				// successfully changing password
      			$user['password']  = md5($_POST['password']);
     			}
  			}
 		}
 		
 		if (! $error){
 			$database->update_array('users', $user, "id = '" . $_POST['userid'] . "'");
  			$success .= $lang['profile_saved'];
 		}
	}
	
	
	
	//GET_ORDERS
	if ($loggedIn){
		$results = $database->select("SELECT * FROM users where id = " . $_SESSION['userid'] . "");
  		//get orders
  		$orders  = $database->select("SELECT * FROM order_sum where uid = " . $_SESSION['userid'] . " ORDER by date ");
  		
  		if ($orders != FALSE) {
  			for ($i = 0; $i < count($orders); $i++) {
  				$results_location        = $database->select("SELECT * FROM locations where id = '" . $orders[$i]['lid'] . "' ");
    			$results_inv             = $database->select("SELECT * FROM order_inv where oid = '" . $orders[$i]['id'] . "' ");
    			$orders[$i]['locations'] = $results_location[0];
    			$orders[$i]['inventory'] = $results_inv;
   		}
  		}
  		
  		$smarty->assign('profile', $results[0]);
  		$smarty->assign('orders', $orders);
	}
	
	
	
	if (!isset($success)){
		$success = "";
	}
	
	$smarty->assign('success', $success);
	$smarty->assign('error', $error);
	$smarty->assign('reg', $loggedIn);
?>